package com.dudu.dao;

import java.sql.Connection;
import java.util.List;
import net.sf.json.JSONObject;
import com.dudu.bean.DictionaryBean;
import core.CoreDao;
import core.db.DBConnectionUtil;

public class DictionaryDao {
	public int insert(CoreDao dao, DictionaryBean bean) {

		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					"INSERT INTO t_dictionary(type, data_key, data_value, comments)");
			sql.append("VALUES(?, ?, ?, ?)");

			List<JSONObject> list = dao.serviceJsonSql(
					con,
					sql.toString(),
					new Object[] { 
						bean.getType(), bean.getData_key(), bean.getData_value(), bean.getComments()				
					});

			JSONObject obj = list.get(0);
			result = obj.optInt("result");

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	public DictionaryBean queryById(CoreDao dao, int id) {

		Connection con = null;
		DictionaryBean result = null;

		try {
			con = DBConnectionUtil.getDBConnection("emate1");

			StringBuffer sql = new StringBuffer(
					"select id, type, data_key, data_value, comments FROM t_dictionary where id=?");
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(),
					new Object[] { id });
			if (list != null && list.size() > 0) {
				List<DictionaryBean> items = dao.covertToBean(list, DictionaryBean.class);
				result = items.get(0);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	public List<JSONObject> queryAll(CoreDao dao) {

		Connection con = null;
		List<JSONObject> result = null;
		
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					" select * from t_dictionary order by type, id asc ");
			result = dao.serviceJsonSql(con, sql.toString(),
					new Object[] { null });

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	public int update(CoreDao dao, DictionaryBean bean) {

		Connection con = null;
		int result = -1;

		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					" UPDATE t_dictionary set type=?, data_key=?, data_value=?, comments=? ");
			sql.append(" where id=?");

			List<JSONObject> list = dao.serviceJsonSql(

					con,
					sql.toString(),
					new Object[] { 
						bean.getType(), bean.getData_key(), bean.getData_value(), bean.getComments(), bean.getId()
					}

			);

			if (list != null && list.size() > 0) {
				list.get(0);
				JSONObject obj = list.get(0);
				result = obj.optInt("result");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
}
